package com.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.Set;

public class NioClient1 {
    public static void client() throws IOException {
        Scanner input = new Scanner(System.in);

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 8899));
        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while (selector.select() > 0) {
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            for (SelectionKey selectionKey : selectionKeys) {
                SocketChannel sc = (SocketChannel) selectionKey.channel();
                if (selectionKey.isValid() && selectionKey.isConnectable()) {
                    System.out.println("---- NioClient  Connectable ; 链接服务器成功！！");
                    byteBuffer.clear();
                    sc.finishConnect();// 完成连接
                    sc.register(selector, SelectionKey.OP_READ);
                    byteBuffer.put((" 服务器已接受客户端的连接 ！！！").getBytes());
                    byteBuffer.flip();
                    sc.write(byteBuffer);

                    // 启动新线程，监听 cmd 输入
                    new Thread(() -> {
                        while (input.hasNext()) {
                            byteBuffer.clear();
                            String msg = input.nextLine();
                            byteBuffer.put(msg.getBytes(StandardCharsets.UTF_8));
                            byteBuffer.flip();
                            try {
                                sc.write(byteBuffer);
                            } catch (IOException e) {
                                e.getLocalizedMessage();
                            }

                        }
                    }).start();
                } else if (selectionKey.isValid() && selectionKey.isReadable()) {
                    byteBuffer.clear();
                    int count = sc.read(byteBuffer);
                    byteBuffer.flip();
                    if (count > 0) {
                        String msg = new String(byteBuffer.array(), 0, count);
                        System.out.println("---- NioClient  Connectable ; 读取服务器信息" + msg);
                    }
//					sc.register(selector,SelectionKey.OP_WRITE);
                }
//				else if(selectionKey.isValid()&&selectionKey.isWritable()){
//					byteBuffer.clear();
//					System.out.println("---- NioClient  Writable -----");
//					sc.register(selector,SelectionKey.OP_READ);
//				}
//				sc.register(selector, SelectionKey.OP_READ);
                selectionKeys.remove(selectionKey);

            }
        }
    }

    public static void main(String[] args) throws IOException {
//		for (int i = 0; i < 10; i++) {
//			new Thread(()->{
//				try { client(); } catch (IOException e) { e.printStackTrace(); }
//			}) .start();
//
//		}
        try {
            client();
        } catch (IOException e) {
            e.getLocalizedMessage();
        }

    }
}
